package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.common.R;
import com.itheima.common.UserHolder;
import com.itheima.pojo.AddressBook;
import com.itheima.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {
    @Autowired
    private AddressBookService addressBookService;

    //新增地址
    @PostMapping
    public R<String> save(@RequestBody AddressBook addressBook){
        //获取userid
        addressBook.setUserId(UserHolder.getCurrentId());//设置id
        addressBookService.save(addressBook);
        return R.success("保存地址成功");
    }

    //设置默认地址
    @PutMapping("/default")
    public R<AddressBook> update(@RequestBody AddressBook addressBook){
        //1.把地址都设为0
        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.set(AddressBook::getIsDefault,0);
        addressBookService.update(qw);
        //在给当前地址设为默认地址
        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }

    //根据id查询
    @GetMapping("/{id}")
    public R<AddressBook> selectById(@PathVariable Long id){
        AddressBook addressBook = addressBookService.getById(id);
        if (addressBook != null){
            return R.success(addressBook);
        }
            return R.error("地址不存在");
    }

    //查询默认地址
    @GetMapping("/default")
    public R<AddressBook> selectDefault(){
        LambdaUpdateWrapper<AddressBook> qw = new LambdaUpdateWrapper<>();
        qw.eq(AddressBook::getIsDefault,1).eq(AddressBook::getUserId,UserHolder.getCurrentId());
        AddressBook one = addressBookService.getOne(qw);
        return R.success(one);
    }

    //查询指定用户的全部地址
    @GetMapping("/list")
    public R<List<AddressBook>> selectAll(){
        Long id = UserHolder.getCurrentId();
        LambdaQueryWrapper<AddressBook> qw = new LambdaQueryWrapper<>();
        qw.eq(AddressBook::getUserId,id);
        List<AddressBook> list = addressBookService.list(qw);
        return R.success(list);
    }

    //删除地址
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }

    //修改地址
    @PutMapping
    public R<AddressBook> updateById(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success(addressBook);
    }
}

